package util;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class SoundManager
{
	private Clip _lineFoundPlayer = null;
	private Clip _starPlacedPlayer = null;
	private File _lineFoundFile = new File(".\\res\\lineFound.wav");
	private File _starPlacedFile = new File(".\\res\\starPlaced.wav");
	
	public SoundManager()
	{
		_starPlacedPlayer = loadSound(_starPlacedFile);
		FloatControl volume = (FloatControl) _starPlacedPlayer.getControl(FloatControl.Type.MASTER_GAIN);
		volume.setValue(-22);
		
		_lineFoundPlayer = loadSound(_lineFoundFile);
		volume = (FloatControl) _lineFoundPlayer.getControl(FloatControl.Type.MASTER_GAIN);
		volume.setValue(0);
	}

	private Clip loadSound(File soundFile)
	{
		Clip clip = null;
		try
		{
			clip = AudioSystem.getClip();
			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
			clip.open(audioInputStream);
		}
		catch (LineUnavailableException e)
		{
			System.err.println("Unable to create audio player");
		}
		catch (UnsupportedAudioFileException e)
		{
			System.err.println("Unsupported audio file: " + soundFile.getName());
		}
		catch (IOException e)
		{
			System.err.println("Unable to load audio file:" + soundFile.getName());
		}
		return clip;
	}
	
	public void lineFull()
	{
		_lineFoundPlayer.stop();
		_lineFoundPlayer.setFramePosition(0);
		_lineFoundPlayer.start();
	}
	
	public void starPlaced()
	{
		_starPlacedPlayer.stop();
		_starPlacedPlayer.setFramePosition(0);
		_starPlacedPlayer.start();
	}
}
